import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  Select, 
  Switch, 
  Space, 
  Popconfirm,
  message,
  Tag,
  Typography
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { apiService } from '../services/apiService';

const { Option } = Select;
const { TextArea } = Input;
const { Text } = Typography;

interface DecisionRule {
  id: number;
  name: string;
  description: string;
  prompt_template: string;
  data_sources: string[];
  is_active: boolean;
  created_at: string;
}

const DecisionRules: React.FC = () => {
  const [rules, setRules] = useState<DecisionRule[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRule, setEditingRule] = useState<DecisionRule | null>(null);
  const [form] = Form.useForm();

  const fetchRules = async () => {
    try {
      setLoading(true);
      const response = await apiService.get('/api/ai-decision/rules');
      if (response.success) {
        setRules(response.rules);
      }
    } catch (err) {
      message.error('获取决策规则失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRules();
  }, []);

  const handleAdd = () => {
    setEditingRule(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: DecisionRule) => {
    setEditingRule(record);
    form.setFieldsValue({
      ...record,
      data_sources: record.data_sources
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await apiService.delete(`/api/ai-decision/rules/${id}`);
      message.success('删除成功');
      fetchRules();
    } catch (err) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingRule) {
        await apiService.put(`/api/ai-decision/rules/${editingRule.id}`, values);
        message.success('更新成功');
      } else {
        await apiService.post('/api/ai-decision/rules', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchRules();
    } catch (err) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '数据源',
      dataIndex: 'data_sources',
      key: 'data_sources',
      render: (sources: string[]) => (
        <Space>
          {sources.map(source => (
            <Tag key={source} color="blue">{source}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '启用' : '停用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: DecisionRule) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个决策规则吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="decision-rules-container page-transition">
      <div className="page-header">
        <h1>⚙️ 决策规则管理</h1>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          添加规则
        </Button>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={rules}
          loading={loading}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingRule ? '编辑决策规则' : '添加决策规则'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="规则名称"
            rules={[{ required: true, message: '请输入规则名称' }]}
          >
            <Input placeholder="请输入规则名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="规则描述"
            rules={[{ required: true, message: '请输入规则描述' }]}
          >
            <TextArea 
              placeholder="请输入规则描述" 
              rows={3}
            />
          </Form.Item>

          <Form.Item
            name="data_sources"
            label="关联数据源"
            rules={[{ required: true, message: '请选择数据源' }]}
          >
            <Select
              mode="multiple"
              placeholder="请选择数据源"
              style={{ width: '100%' }}
            >
              <Option value="weather">天气数据</Option>
              <Option value="covid">疫情数据</Option>
              <Option value="flu">流感数据</Option>
              <Option value="traffic">交通数据</Option>
              <Option value="air_quality">空气质量</Option>
              <Option value="economic">经济数据</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="prompt_template"
            label="AI提示词模板"
            rules={[{ required: true, message: '请输入提示词模板' }]}
          >
            <TextArea 
              placeholder="请输入AI提示词模板，用于指导AI如何分析数据和提供建议" 
              rows={8}
            />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="是否启用"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingRule ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DecisionRules;
